<?php

namespace app\index\model;

use think\facade\Session;
use think\Model;

class Msg extends Model
{
    public function userData()
    {
        return $this->hasOne(User::class , 'id' , 'send_uid');
    }
    /** 
     * @param int sendId 发送者ID
     * @param int receiverId 接收者ID
     * @param array param 请求需要用到的参数 content发送内容必填(请求类型：0为系统消息 1为好友消息article_id 2 好友相关 user_id)
     * $param = ['content' => '内容' , 'article_id' => 1]
     */
    public static function send($sendId, $receiverId,  $param = [])
    {
        if(!array_key_exists('type',$param))  $param['type'] = 0;
        else  $param['type'] = 1;
        if(self::checkMsgType($param) == 1){
            $data['send_uid'] = $sendId;
            $data['receiver_uid'] = $receiverId;
            $data['content'] = remove_xss($param['content']);
            foreach ($param as $k => $v) {
                $data[$k] = $v;
            }
            $res = self::create($data);
            if ($res) return 1;
            return 0;
        }
        
    }
    // 检查参数 返回为 1时则发送消息
    public static function checkMsgType($param = [])
    {
        switch ($param['type']) {
            case 1:
                if(empty($param['article_id'])) return -1;
                // 检查发送的文章是否是自己的 ， 是则不发送消息
                $authorId = Article::find($param['article_id'])->user_id;
                if ($authorId == Session::get('user.user_id')) {
                    return 0;
                }
            break;
        }
        return 1;
    }
    public static function list($limit)
    {
        $list = self::with(['userData' => function($query) {
            $query->field('id,username');
        }])
        ->where('receiver_uid', Session::get('user.user_id'))
        ->order('status asc,id desc')->paginate($limit);
        $data = ['list' => $list, 'count' => $list->total()];
        return success($data, '获取成功', 0);
    }
    public function read() {}
}
